<?php

declare(strict_types=1);

namespace app\common\model;

use addons\Target\facade\Target;

use app\common\controller\Config;
use think\Exception;
use think\facade\Cache;
use think\facade\Event;

/**
 * @mixin \think\Model
 */
class Relation extends Base
{

    protected $name = 'user_relation';

    public function getAll($param)
    {
        try {

            return $this->where($param)->select()->toArray();
        } catch (\Exception $e) {
            return [];
        }
    }

    protected function user()
    {
        return $this->hasOne(User::class, 'id', 'uid')
            ->field('id,code,nickname,mobile,is_active,level_id');
    }

    protected function fresh()
    {
        return $this->hasOne(User::class, 'id', 'new_uid')
            ->field('id,code,photo,nickname,mobile,team_total,level_id')->with('level');
    }

    public static function generate(int $new_uid, $new_code, int $parentId, string $parentCode): bool
    {
        try {
            parent::create([
                'uid'      => $parentId,
                'code'     => $parentCode,
                'algebra'  => 1,
                'new_uid'  => $new_uid,
                'new_code' => $new_code,
            ]);
            $time = time();

            parent::where('new_uid', $parentId)
                ->field('uid,code,algebra + 1 as algebra,' . $time . ' as create_time,' . $time . ' as update_time,' . $new_uid . ' as new_uid,"' . $new_code . '" as new_code')
                ->selectInsert([
                    'uid',
                    'code',
                    'algebra',
                    'create_time',
                    'update_time',
                    'new_uid',
                    'new_code',
                ], (new static())->getName());

            return true;
        } catch (\Exception $e) {
            throw new Exception($e->getMessage());
        }
    }

    /**
     * @param $amount - 金额
     * @param $uid - 会员ID
     * @param string $key - 团队业绩key
     * 原点 2021年12月28日11:50:17 更新团队业绩
     */
    public static function renewTeamTotal($amount, $uid, $key = 'team_total')
    {
        $all_id = parent::where('new_uid', $uid)->column('uid');
        if (!empty($all_id)) {
            User::whereIn('id', $all_id)->inc($key, floatval($amount))->update();
        }
    }



    /**
     * @param $uid
     * @return array
     * 原点 2023年5月12日17:01:26 升级
     */
    public static function upgrade($uid): array
    {
        try {
            $list = parent::with('user')->where('new_uid', $uid)
                ->field('id,uid,algebra')->order('algebra', 'asc')->select();

            foreach ($list as $item) {
                $min_total = User::geMinTeam($item->user->id);
                $level = Level::where('id', '>', $item->user->level_id)
                    ->where('min_team', '<=', $min_total)
                    ->order('id', 'desc')
                    ->find();
                if ($level) {
                    User::update(['level_id' => $level->id, 'id' => $item->uid]);
                }
            }
            return ['code' => 1, 'msg' => 'success'];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 奖金设置
     */
    public static function tpMoney($money, $user, $type = 1)
    {
        parent::startTrans();
        $sys = Config::lists();
        $expend_money = 0; //奖金支出
        $tp_money = 0; //推荐奖
        $hand_money = 0; //传递奖
        try {
            switch ($type) {
                case 1:
                    /**
                     * 推荐奖
                     */
                    if ($user->parent_id != 0) {
                        $tp_money = round($money * $sys['tp_1'], 2);
                        Target::Account()->basics($user->parent_id, 'bonus', $tp_money, '直推奖励', '+')
                            ->createBonus($user->id, 1);
                        $upuser = User::find($user->parent_id);
                        /**
                         *传递收益
                         */
                        $list = self::getTeamList($upuser, 11);
                        if ($list['code'] == 1) {
                            if (!empty($list['list'])) {
                                foreach ($list['list'] as $item) {
                                    $tp_money1 = round($money * $sys['tp_1'] * $item['bl'], 2);
                                    Target::Account()->basics($item['uid'], 'bonus', $tp_money1, '传递收益', '+')
                                        ->createBonus($user->id, 2);
                                    $hand_money += $tp_money1;
                                }
                            }
                        }
                    }
                    $expend_money = $tp_money + $hand_money;
                    break;
                case 2:
                    /**
                     * 分享收益
                     */
                    // print('<pre>');print_r($user);die;
                    if ($user->parent_id != 0) {
                        $share_money = $expend_money = round($money * $sys['share'], 2);
                        Target::Account()->basics($user->parent_id, 'bonus', $share_money, '分享收益', '+')
                            ->createBonus($user->id, 3);
                    }
                    break;
                default:
                    break;
            }
            Event::trigger('Statistics', ['key' => 'expend', 'value' => $expend_money]);
            parent::commit();
            return ['code' => 11, 'msg' => '成功'];
        } catch (\Exception $e) {
            parent::rollback();
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 获取团队列表
     */
    public static function getTeamList($user, $level = 1)
    {
        $arr = [];
        $sys = Config::lists();
        try {
            $list = parent::with('user')->where('new_uid', $user->id)
                ->field('id,uid,algebra')->order('algebra', 'asc')->limit($level)->select();
            foreach ($list as $k => $v) {
                $bl = $sys['hand_1'] * pow($sys['hand_2'], ($v['algebra'] - 1)); //传递比例
                $num = self::getTeamNum($v->uid);
                $count = UserHand::where('algebra', $v->algebra)->value('count');
                if ($num >= $count) {
                    $data['uid'] = $v->uid;
                    $data['bl'] = $bl;
                    $arr[] = $data;
                }
            }
            return ['code' => 1, 'msg' => '获取成功', 'list' => $arr];
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
    /**
     * 获取直推人数
     */
    public static function getTeamNum($uid)
    {
        $num = 0;
        try {
            $list = parent::where(['uid' => $uid, 'algebra' => 1])->column('new_uid');
            $num = User::whereIn('id', $list)->where('level_id', 2)->count();
            return $num;
        } catch (\Exception $e) {
            return ['code' => -1, 'msg' => $e->getMessage()];
        }
    }
}
